package cn.janus.util;

import cn.janus.component.CustomClaims;
import cn.janus.eum.TimeMillisEnum;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.function.Function;

@Component
public class JwtUtil {


    private final String secretKey = UUID.randomUUID().toString().replace("-", "");

    public String generateToken(String userId, Set<String> roles) {
        Claims claims = CustomClaims
                .builder()
                .setRoles(roles)
                .setSubject(userId)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + TimeMillisEnum.ONE_DAY.getTime())); // 单位毫秒
        return Jwts
                .builder()
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .setClaims(claims)
                .compact();


    }

    public Boolean validateToken(String token) {
        return !isTokenExpired(token);
    }

    public Date extractExpiration(String token) {
        return extractClaim(token, Claims::getExpiration);
    }

    public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
        return claimsResolver.apply(extractAllClaims(token));
    }

    public Claims extractAllClaims(String token) {
        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
    }

    private Boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }
}